home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / smtplib.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  29KB  |  899 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''SMTP/ESMTP client class.
  5.  
  6. This should follow RFC 821 (SMTP), RFC 1869 (ESMTP), RFC 2554 (SMTP
  7. Authentication) and RFC 2487 (Secure SMTP over TLS).
  8.  
  9. Notes:
  10.  
  11. Please remember, when doing ESMTP, that the names of the SMTP service
  12. extensions are NOT the same thing as the option keywords for the RCPT
  13. and MAIL commands!
  14.  
  15. Example:
  16.  
  17.   >>> import smtplib
  18.   >>> s=smtplib.SMTP("localhost")
  19.   >>> print s.help()
  20.   This is Sendmail version 8.8.4
  21.   Topics:
  22.       HELO    EHLO    MAIL    RCPT    DATA
  23.       RSET    NOOP    QUIT    HELP    VRFY
  24.       EXPN    VERB    ETRN    DSN
  25.   For more info use "HELP <topic>".
  26.   To report bugs in the implementation send email to
  27.       sendmail-bugs@sendmail.org.
  28.   For local information send email to Postmaster at your site.
  29.   End of HELP info
  30.   >>> s.putcmd("vrfy","someone@here")
  31.   >>> s.getreply()
  32.   (250, "Somebody OverHere <somebody@here.my.org>")
  33.   >>> s.quit()
  34. '''
  35. import socket
  36. import re
  37. import email.utils as email
  38. import base64
  39. import hmac
  40. from email.base64mime import encode as encode_base64
  41. from sys import stderr
  42. __all__ = [
  43.     'SMTPException',
  44.     'SMTPServerDisconnected',
  45.     'SMTPResponseException',
  46.     'SMTPSenderRefused',
  47.     'SMTPRecipientsRefused',
  48.     'SMTPDataError',
  49.     'SMTPConnectError',
  50.     'SMTPHeloError',
  51.     'SMTPAuthenticationError',
  52.     'quoteaddr',
  53.     'quotedata',
  54.     'SMTP']
  55. SMTP_PORT = 25
  56. SMTP_SSL_PORT = 465
  57. CRLF = '\r\n'
  58. OLDSTYLE_AUTH = re.compile('auth=(.*)', re.I)
  59.  
  60. class SMTPException(Exception):
  61.     '''Base class for all exceptions raised by this module.'''
  62.     pass
  63.  
  64.  
  65. class SMTPServerDisconnected(SMTPException):
  66.     '''Not connected to any SMTP server.
  67.  
  68.     This exception is raised when the server unexpectedly disconnects,
  69.     or when an attempt is made to use the SMTP instance before
  70.     connecting it to a server.
  71.     '''
  72.     pass
  73.  
  74.  
  75. class SMTPResponseException(SMTPException):
  76.     """Base class for all exceptions that include an SMTP error code.
  77.  
  78.     These exceptions are generated in some instances when the SMTP
  79.     server returns an error code.  The error code is stored in the
  80.     `smtp_code' attribute of the error, and the `smtp_error' attribute
  81.     is set to the error message.
  82.     """
  83.     
  84.     def __init__(self, code, msg):
  85.         self.smtp_code = code
  86.         self.smtp_error = msg
  87.         self.args = (code, msg)
  88.  
  89.  
  90.  
  91. class SMTPSenderRefused(SMTPResponseException):
  92.     """Sender address refused.
  93.  
  94.     In addition to the attributes set by on all SMTPResponseException
  95.     exceptions, this sets `sender' to the string that the SMTP refused.
  96.     """
  97.     
  98.     def __init__(self, code, msg, sender):
  99.         self.smtp_code = code
  100.         self.smtp_error = msg
  101.         self.sender = sender
  102.         self.args = (code, msg, sender)
  103.  
  104.  
  105.  
  106. class SMTPRecipientsRefused(SMTPException):
  107.     """All recipient addresses refused.
  108.  
  109.     The errors for each recipient are accessible through the attribute
  110.     'recipients', which is a dictionary of exactly the same sort as
  111.     SMTP.sendmail() returns.
  112.     """
  113.     
  114.     def __init__(self, recipients):
  115.         self.recipients = recipients
  116.         self.args = (recipients,)
  117.  
  118.  
  119.  
  120. class SMTPDataError(SMTPResponseException):
  121.     """The SMTP server didn't accept the data."""
  122.     pass
  123.  
  124.  
  125. class SMTPConnectError(SMTPResponseException):
  126.     '''Error during connection establishment.'''
  127.     pass
  128.  
  129.  
  130. class SMTPHeloError(SMTPResponseException):
  131.     '''The server refused our HELO reply.'''
  132.     pass
  133.  
  134.  
  135. class SMTPAuthenticationError(SMTPResponseException):
  136.     """Authentication error.
  137.  
  138.     Most probably the server didn't accept the username/password
  139.     combination provided.
  140.     """
  141.     pass
  142.  
  143.  
  144. def quoteaddr(addr):
  145.     '''Quote a subset of the email addresses defined by RFC 821.
  146.  
  147.     Should be able to handle anything rfc822.parseaddr can handle.
  148.     '''
  149.     m = (None, None)
  150.     
  151.     try:
  152.         m = email.utils.parseaddr(addr)[1]
  153.     except AttributeError:
  154.         pass
  155.  
  156.     if m == (None, None):
  157.         return '<%s>' % addr
  158.     if m is None:
  159.         return '<>'
  160.     return '<%s>' % m
  161.  
  162.  
  163. def quotedata(data):
  164.     """Quote data for email.
  165.  
  166.     Double leading '.', and change Unix newline '\\n', or Mac '\\r' into
  167.     Internet CRLF end-of-line.
  168.     """
  169.     return re.sub('(?m)^\\.', '..', re.sub('(?:\\r\\n|\\n|\\r(?!\\n))', CRLF, data))
  170.  
  171.  
  172. try:
  173.     import ssl
  174. except ImportError:
  175.     _have_ssl = False
  176.  
  177.  
  178. class SSLFakeFile:
  179.     '''A fake file like object that really wraps a SSLObject.
  180.  
  181.         It only supports what is needed in smtplib.
  182.         '''
  183.     
  184.     def __init__(self, sslobj):
  185.         self.sslobj = sslobj
  186.  
  187.     
  188.     def readline(self):
  189.         str = ''
  190.         chr = None
  191.         while chr != '\n':
  192.             chr = self.sslobj.read(1)
  193.             if not chr:
  194.                 break
  195.             
  196.             str += chr
  197.         return str
  198.  
  199.     
  200.     def close(self):
  201.         pass
  202.  
  203.  
  204. _have_ssl = True
  205.  
  206. class SMTP:
  207.     """This class manages a connection to an SMTP or ESMTP server.
  208.     SMTP Objects:
  209.         SMTP objects have the following attributes:
  210.             helo_resp
  211.                 This is the message given by the server in response to the
  212.                 most recent HELO command.
  213.  
  214.             ehlo_resp
  215.                 This is the message given by the server in response to the
  216.                 most recent EHLO command. This is usually multiline.
  217.  
  218.             does_esmtp
  219.                 This is a True value _after you do an EHLO command_, if the
  220.                 server supports ESMTP.
  221.  
  222.             esmtp_features
  223.                 This is a dictionary, which, if the server supports ESMTP,
  224.                 will _after you do an EHLO command_, contain the names of the
  225.                 SMTP service extensions this server supports, and their
  226.                 parameters (if any).
  227.  
  228.                 Note, all extension names are mapped to lower case in the
  229.                 dictionary.
  230.  
  231.         See each method's docstrings for details.  In general, there is a
  232.         method of the same name to perform each SMTP command.  There is also a
  233.         method called 'sendmail' that will do an entire mail transaction.
  234.         """
  235.     debuglevel = 0
  236.     file = None
  237.     helo_resp = None
  238.     ehlo_msg = 'ehlo'
  239.     ehlo_resp = None
  240.     does_esmtp = 0
  241.     
  242.     def __init__(self, host = '', port = 0, local_hostname = None, timeout = socket._GLOBAL_DEFAULT_TIMEOUT):
  243.         """Initialize a new instance.
  244.  
  245.         If specified, `host' is the name of the remote host to which to
  246.         connect.  If specified, `port' specifies the port to which to connect.
  247.         By default, smtplib.SMTP_PORT is used.  An SMTPConnectError is raised
  248.         if the specified `host' doesn't respond correctly.  If specified,
  249.         `local_hostname` is used as the FQDN of the local host.  By default,
  250.         the local hostname is found using socket.getfqdn().
  251.  
  252.         """
  253.         self.timeout = timeout
  254.         self.esmtp_features = { }
  255.         self.default_port = SMTP_PORT
  256.         if host:
  257.             (code, msg) = self.connect(host, port)
  258.             if code != 220:
  259.                 raise SMTPConnectError(code, msg)
  260.             code != 220
  261.         
  262.         if local_hostname is not None:
  263.             self.local_hostname = local_hostname
  264.         else:
  265.             fqdn = socket.getfqdn()
  266.             if '.' in fqdn:
  267.                 self.local_hostname = fqdn
  268.             else:
  269.                 addr = '127.0.0.1'
  270.                 
  271.                 try:
  272.                     addr = socket.gethostbyname(socket.gethostname())
  273.                 except socket.gaierror:
  274.                     pass
  275.  
  276.                 self.local_hostname = '[%s]' % addr
  277.  
  278.     
  279.     def set_debuglevel(self, debuglevel):
  280.         '''Set the debug output level.
  281.  
  282.         A non-false value results in debug messages for connection and for all
  283.         messages sent to and received from the server.
  284.  
  285.         '''
  286.         self.debuglevel = debuglevel
  287.  
  288.     
  289.     def _get_socket(self, port, host, timeout):
  290.         if self.debuglevel > 0:
  291.             print >>stderr, 'connect:', (host, port)
  292.         
  293.         return socket.create_connection((port, host), timeout)
  294.  
  295.     
  296.     def connect(self, host = 'localhost', port = 0):
  297.         """Connect to a host on a given port.
  298.  
  299.         If the hostname ends with a colon (`:') followed by a number, and
  300.         there is no port specified, that suffix will be stripped off and the
  301.         number interpreted as the port number to use.
  302.  
  303.         Note: This method is automatically invoked by __init__, if a host is
  304.         specified during instantiation.
  305.  
  306.         """
  307.         if not port and host.find(':') == host.rfind(':'):
  308.             i = host.rfind(':')
  309.             if i >= 0:
  310.                 host = host[:i]
  311.                 port = host[i + 1:]
  312.                 
  313.                 try:
  314.                     port = int(port)
  315.                 except ValueError:
  316.                     raise socket.error, 'nonnumeric port'
  317.                 except:
  318.                     None<EXCEPTION MATCH>ValueError
  319.                 
  320.  
  321.             None<EXCEPTION MATCH>ValueError
  322.         
  323.         if not port:
  324.             port = self.default_port
  325.         
  326.         if self.debuglevel > 0:
  327.             print >>stderr, 'connect:', (host, port)
  328.         
  329.         self.sock = self._get_socket(host, port, self.timeout)
  330.         (code, msg) = self.getreply()
  331.         if self.debuglevel > 0:
  332.             print >>stderr, 'connect:', msg
  333.         
  334.         return (code, msg)
  335.  
  336.     
  337.     def send(self, str):
  338.         """Send `str' to the server."""
  339.         if self.debuglevel > 0:
  340.             print >>stderr, 'send:', repr(str)
  341.         
  342.         if hasattr(self, 'sock') and self.sock:
  343.             
  344.             try:
  345.                 self.sock.sendall(str)
  346.             except socket.error:
  347.                 self.close()
  348.                 raise SMTPServerDisconnected('Server not connected')
  349.             except:
  350.                 None<EXCEPTION MATCH>socket.error
  351.             
  352.  
  353.         None<EXCEPTION MATCH>socket.error
  354.         raise SMTPServerDisconnected('please run connect() first')
  355.  
  356.     
  357.     def putcmd(self, cmd, args = ''):
  358.         '''Send a command to the server.'''
  359.         if args == '':
  360.             str = '%s%s' % (cmd, CRLF)
  361.         else:
  362.             str = '%s %s%s' % (cmd, args, CRLF)
  363.         self.send(str)
  364.  
  365.     
  366.     def getreply(self):
  367.         """Get a reply from the server.
  368.  
  369.         Returns a tuple consisting of:
  370.  
  371.           - server response code (e.g. '250', or such, if all goes well)
  372.             Note: returns -1 if it can't read response code.
  373.  
  374.           - server response string corresponding to response code (multiline
  375.             responses are converted to a single, multiline string).
  376.  
  377.         Raises SMTPServerDisconnected if end-of-file is reached.
  378.         """
  379.         resp = []
  380.         if self.file is None:
  381.             self.file = self.sock.makefile('rb')
  382.         
  383.         while None:
  384.             line = self.file.readline()
  385.             if line == '':
  386.                 self.close()
  387.                 raise SMTPServerDisconnected('Connection unexpectedly closed')
  388.             if self.debuglevel > 0:
  389.                 print >>stderr, 'reply:', repr(line)
  390.             
  391.             resp.append(line[4:].strip())
  392.             code = line[:3]
  393.             
  394.             try:
  395.                 errcode = int(code)
  396.             except ValueError:
  397.                 errcode = -1
  398.                 break
  399.  
  400.             if line[3:4] != '-':
  401.                 break
  402.                 continue
  403.             continue
  404.             errmsg = '\n'.join(resp)
  405.             if self.debuglevel > 0:
  406.                 print >>stderr, 'reply: retcode (%s); Msg: %s' % (errcode, errmsg)
  407.             
  408.         return (errcode, errmsg)
  409.  
  410.     
  411.     def docmd(self, cmd, args = ''):
  412.         '''Send a command, and return its response code.'''
  413.         self.putcmd(cmd, args)
  414.         return self.getreply()
  415.  
  416.     
  417.     def helo(self, name = ''):
  418.         """SMTP 'helo' command.
  419.         Hostname to send for this command defaults to the FQDN of the local
  420.         host.
  421.         """
  422.         if not name:
  423.             pass
  424.         self.putcmd('helo', self.local_hostname)
  425.         (code, msg) = self.getreply()
  426.         self.helo_resp = msg
  427.         return (code, msg)
  428.  
  429.     
  430.     def ehlo(self, name = ''):
  431.         """ SMTP 'ehlo' command.
  432.         Hostname to send for this command defaults to the FQDN of the local
  433.         host.
  434.         """
  435.         self.esmtp_features = { }
  436.         if not name:
  437.             pass
  438.         self.putcmd(self.ehlo_msg, self.local_hostname)
  439.         (code, msg) = self.getreply()
  440.         if code == -1 and len(msg) == 0:
  441.             self.close()
  442.             raise SMTPServerDisconnected('Server not connected')
  443.         len(msg) == 0
  444.         self.ehlo_resp = msg
  445.         if code != 250:
  446.             return (code, msg)
  447.         self.does_esmtp = 1
  448.         resp = self.ehlo_resp.split('\n')
  449.         del resp[0]
  450.         for each in resp:
  451.             auth_match = OLDSTYLE_AUTH.match(each)
  452.             if auth_match:
  453.                 self.esmtp_features['auth'] = self.esmtp_features.get('auth', '') + ' ' + auth_match.groups(0)[0]
  454.                 continue
  455.             
  456.             m = re.match('(?P<feature>[A-Za-z0-9][A-Za-z0-9\\-]*) ?', each)
  457.             if m:
  458.                 feature = m.group('feature').lower()
  459.                 params = m.string[m.end('feature'):].strip()
  460.                 if feature == 'auth':
  461.                     self.esmtp_features[feature] = self.esmtp_features.get(feature, '') + ' ' + params
  462.                 else:
  463.                     self.esmtp_features[feature] = params
  464.             feature == 'auth'
  465.         
  466.         return (code, msg)
  467.  
  468.     
  469.     def has_extn(self, opt):
  470.         '''Does the server support a given SMTP service extension?'''
  471.         return opt.lower() in self.esmtp_features
  472.  
  473.     
  474.     def help(self, args = ''):
  475.         """SMTP 'help' command.
  476.         Returns help text from server."""
  477.         self.putcmd('help', args)
  478.         return self.getreply()[1]
  479.  
  480.     
  481.     def rset(self):
  482.         """SMTP 'rset' command -- resets session."""
  483.         return self.docmd('rset')
  484.  
  485.     
  486.     def noop(self):
  487.         """SMTP 'noop' command -- doesn't do anything :>"""
  488.         return self.docmd('noop')
  489.  
  490.     
  491.     def mail(self, sender, options = []):
  492.         """SMTP 'mail' command -- begins mail xfer session."""
  493.         optionlist = ''
  494.         if options and self.does_esmtp:
  495.             optionlist = ' ' + ' '.join(options)
  496.         
  497.         self.putcmd('mail', 'FROM:%s%s' % (quoteaddr(sender), optionlist))
  498.         return self.getreply()
  499.  
  500.     
  501.     def rcpt(self, recip, options = []):
  502.         """SMTP 'rcpt' command -- indicates 1 recipient for this mail."""
  503.         optionlist = ''
  504.         if options and self.does_esmtp:
  505.             optionlist = ' ' + ' '.join(options)
  506.         
  507.         self.putcmd('rcpt', 'TO:%s%s' % (quoteaddr(recip), optionlist))
  508.         return self.getreply()
  509.  
  510.     
  511.     def data(self, msg):
  512.         """SMTP 'DATA' command -- sends message data to server.
  513.  
  514.         Automatically quotes lines beginning with a period per rfc821.
  515.         Raises SMTPDataError if there is an unexpected reply to the
  516.         DATA command; the return value from this method is the final
  517.         response code received when the all data is sent.
  518.         """
  519.         self.putcmd('data')
  520.         (code, repl) = self.getreply()
  521.         if self.debuglevel > 0:
  522.             print >>stderr, 'data:', (code, repl)
  523.         
  524.         if code != 354:
  525.             raise SMTPDataError(code, repl)
  526.         code != 354
  527.         q = quotedata(msg)
  528.         if q[-2:] != CRLF:
  529.             q = q + CRLF
  530.         
  531.         q = q + '.' + CRLF
  532.         self.send(q)
  533.         (code, msg) = self.getreply()
  534.         if self.debuglevel > 0:
  535.             print >>stderr, 'data:', (code, msg)
  536.         
  537.         return (code, msg)
  538.  
  539.     
  540.     def verify(self, address):
  541.         """SMTP 'verify' command -- checks for address validity."""
  542.         self.putcmd('vrfy', quoteaddr(address))
  543.         return self.getreply()
  544.  
  545.     vrfy = verify
  546.     
  547.     def expn(self, address):
  548.         """SMTP 'expn' command -- expands a mailing list."""
  549.         self.putcmd('expn', quoteaddr(address))
  550.         return self.getreply()
  551.  
  552.     
  553.     def ehlo_or_helo_if_needed(self):
  554.         """Call self.ehlo() and/or self.helo() if needed.
  555.  
  556.         If there has been no previous EHLO or HELO command this session, this
  557.         method tries ESMTP EHLO first.
  558.  
  559.         This method may raise the following exceptions:
  560.  
  561.          SMTPHeloError            The server didn't reply properly to
  562.                                   the helo greeting.
  563.         """
  564.         if self.helo_resp is None and self.ehlo_resp is None:
  565.             if self.ehlo()[0] <= self.ehlo()[0]:
  566.                 pass
  567.             elif not self.ehlo()[0] <= 299:
  568.                 (code, resp) = self.helo()
  569.                 if code <= code:
  570.                     pass
  571.                 elif not code <= 299:
  572.                     raise SMTPHeloError(code, resp)
  573.                 
  574.             
  575.         
  576.  
  577.     
  578.     def login(self, user, password):
  579.         """Log in on an SMTP server that requires authentication.
  580.  
  581.         The arguments are:
  582.             - user:     The user name to authenticate with.
  583.             - password: The password for the authentication.
  584.  
  585.         If there has been no previous EHLO or HELO command this session, this
  586.         method tries ESMTP EHLO first.
  587.  
  588.         This method will return normally if the authentication was successful.
  589.  
  590.         This method may raise the following exceptions:
  591.  
  592.          SMTPHeloError            The server didn't reply properly to
  593.                                   the helo greeting.
  594.          SMTPAuthenticationError  The server didn't accept the username/
  595.                                   password combination.
  596.          SMTPException            No suitable authentication method was
  597.                                   found.
  598.         """
  599.         
  600.         def encode_cram_md5(challenge, user, password):
  601.             challenge = base64.decodestring(challenge)
  602.             response = user + ' ' + hmac.HMAC(password, challenge).hexdigest()
  603.             return encode_base64(response, eol = '')
  604.  
  605.         
  606.         def encode_plain(user, password):
  607.             return encode_base64('\x00%s\x00%s' % (user, password), eol = '')
  608.  
  609.         AUTH_PLAIN = 'PLAIN'
  610.         AUTH_CRAM_MD5 = 'CRAM-MD5'
  611.         AUTH_LOGIN = 'LOGIN'
  612.         self.ehlo_or_helo_if_needed()
  613.         if not self.has_extn('auth'):
  614.             raise SMTPException('SMTP AUTH extension not supported by server.')
  615.         self.has_extn('auth')
  616.         authlist = self.esmtp_features['auth'].split()
  617.         preferred_auths = [
  618.             AUTH_CRAM_MD5,
  619.             AUTH_PLAIN,
  620.             AUTH_LOGIN]
  621.         authmethod = None
  622.         for method in preferred_auths:
  623.             if method in authlist:
  624.                 authmethod = method
  625.                 break
  626.                 continue
  627.         
  628.         if authmethod == AUTH_CRAM_MD5:
  629.             (code, resp) = self.docmd('AUTH', AUTH_CRAM_MD5)
  630.             if code == 503:
  631.                 return (code, resp)
  632.             (code, resp) = self.docmd(encode_cram_md5(resp, user, password))
  633.         elif authmethod == AUTH_PLAIN:
  634.             (code, resp) = self.docmd('AUTH', AUTH_PLAIN + ' ' + encode_plain(user, password))
  635.         elif authmethod == AUTH_LOGIN:
  636.             (code, resp) = self.docmd('AUTH', '%s %s' % (AUTH_LOGIN, encode_base64(user, eol = '')))
  637.             if code != 334:
  638.                 raise SMTPAuthenticationError(code, resp)
  639.             code != 334
  640.             (code, resp) = self.docmd(encode_base64(password, eol = ''))
  641.         elif authmethod is None:
  642.             raise SMTPException('No suitable authentication method found.')
  643.         
  644.         if code not in (235, 503):
  645.             raise SMTPAuthenticationError(code, resp)
  646.         code not in (235, 503)
  647.         return (code, resp)
  648.  
  649.     
  650.     def starttls(self, keyfile = None, certfile = None):
  651.         """Puts the connection to the SMTP server into TLS mode.
  652.  
  653.         If there has been no previous EHLO or HELO command this session, this
  654.         method tries ESMTP EHLO first.
  655.  
  656.         If the server supports TLS, this will encrypt the rest of the SMTP
  657.         session. If you provide the keyfile and certfile parameters,
  658.         the identity of the SMTP server and client can be checked. This,
  659.         however, depends on whether the socket module really checks the
  660.         certificates.
  661.  
  662.         This method may raise the following exceptions:
  663.  
  664.          SMTPHeloError            The server didn't reply properly to
  665.                                   the helo greeting.
  666.         """
  667.         self.ehlo_or_helo_if_needed()
  668.         if not self.has_extn('starttls'):
  669.             raise SMTPException('STARTTLS extension not supported by server.')
  670.         self.has_extn('starttls')
  671.         (resp, reply) = self.docmd('STARTTLS')
  672.         if resp == 220:
  673.             if not _have_ssl:
  674.                 raise RuntimeError('No SSL support included in this Python')
  675.             _have_ssl
  676.             self.sock = ssl.wrap_socket(self.sock, keyfile, certfile)
  677.             self.file = SSLFakeFile(self.sock)
  678.             self.helo_resp = None
  679.             self.ehlo_resp = None
  680.             self.esmtp_features = { }
  681.             self.does_esmtp = 0
  682.         
  683.         return (resp, reply)
  684.  
  685.     
  686.     def sendmail(self, from_addr, to_addrs, msg, mail_options = [], rcpt_options = []):
  687.         '''This command performs an entire mail transaction.
  688.  
  689.         The arguments are:
  690.             - from_addr    : The address sending this mail.
  691.             - to_addrs     : A list of addresses to send this mail to.  A bare
  692.                              string will be treated as a list with 1 address.
  693.             - msg          : The message to send.
  694.             - mail_options : List of ESMTP options (such as 8bitmime) for the
  695.                              mail command.
  696.             - rcpt_options : List of ESMTP options (such as DSN commands) for
  697.                              all the rcpt commands.
  698.  
  699.         If there has been no previous EHLO or HELO command this session, this
  700.         method tries ESMTP EHLO first.  If the server does ESMTP, message size
  701.         and each of the specified options will be passed to it.  If EHLO
  702.         fails, HELO will be tried and ESMTP options suppressed.
  703.  
  704.         This method will return normally if the mail is accepted for at least
  705.         one recipient.  It returns a dictionary, with one entry for each
  706.         recipient that was refused.  Each entry contains a tuple of the SMTP
  707.         error code and the accompanying error message sent by the server.
  708.  
  709.         This method may raise the following exceptions:
  710.  
  711.          SMTPHeloError          The server didn\'t reply properly to
  712.                                 the helo greeting.
  713.          SMTPRecipientsRefused  The server rejected ALL recipients
  714.                                 (no mail was sent).
  715.          SMTPSenderRefused      The server didn\'t accept the from_addr.
  716.          SMTPDataError          The server replied with an unexpected
  717.                                 error code (other than a refusal of
  718.                                 a recipient).
  719.  
  720.         Note: the connection will be open even after an exception is raised.
  721.  
  722.         Example:
  723.  
  724.          >>> import smtplib
  725.          >>> s=smtplib.SMTP("localhost")
  726.          >>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"]
  727.          >>> msg = \'\'\'\\
  728.          ... From: Me@my.org
  729.          ... Subject: testin\'...
  730.          ...
  731.          ... This is a test \'\'\'
  732.          >>> s.sendmail("me@my.org",tolist,msg)
  733.          { "three@three.org" : ( 550 ,"User unknown" ) }
  734.          >>> s.quit()
  735.  
  736.         In the above example, the message was accepted for delivery to three
  737.         of the four addresses, and one was rejected, with the error code
  738.         550.  If all addresses are accepted, then the method will return an
  739.         empty dictionary.
  740.  
  741.         '''
  742.         self.ehlo_or_helo_if_needed()
  743.         esmtp_opts = []
  744.         if self.does_esmtp:
  745.             if self.has_extn('size'):
  746.                 esmtp_opts.append('size=%d' % len(msg))
  747.             
  748.             for option in mail_options:
  749.                 esmtp_opts.append(option)
  750.             
  751.         
  752.         (code, resp) = self.mail(from_addr, esmtp_opts)
  753.         if code != 250:
  754.             self.rset()
  755.             raise SMTPSenderRefused(code, resp, from_addr)
  756.         code != 250
  757.         senderrs = { }
  758.         if isinstance(to_addrs, basestring):
  759.             to_addrs = [
  760.                 to_addrs]
  761.         
  762.         for each in to_addrs:
  763.             (code, resp) = self.rcpt(each, rcpt_options)
  764.             if code != 250 and code != 251:
  765.                 senderrs[each] = (code, resp)
  766.                 continue
  767.         
  768.         if len(senderrs) == len(to_addrs):
  769.             self.rset()
  770.             raise SMTPRecipientsRefused(senderrs)
  771.         len(senderrs) == len(to_addrs)
  772.         (code, resp) = self.data(msg)
  773.         if code != 250:
  774.             self.rset()
  775.             raise SMTPDataError(code, resp)
  776.         code != 250
  777.         return senderrs
  778.  
  779.     
  780.     def close(self):
  781.         '''Close the connection to the SMTP server.'''
  782.         if self.file:
  783.             self.file.close()
  784.         
  785.         self.file = None
  786.         if self.sock:
  787.             self.sock.close()
  788.         
  789.         self.sock = None
  790.  
  791.     
  792.     def quit(self):
  793.         '''Terminate the SMTP session.'''
  794.         res = self.docmd('quit')
  795.         self.close()
  796.         return res
  797.  
  798.  
  799. if _have_ssl:
  800.     
  801.     class SMTP_SSL(SMTP):
  802.         """ This is a subclass derived from SMTP that connects over an SSL encrypted
  803.         socket (to use this class you need a socket module that was compiled with SSL
  804.         support). If host is not specified, '' (the local host) is used. If port is
  805.         omitted, the standard SMTP-over-SSL port (465) is used. keyfile and certfile
  806.         are also optional - they can contain a PEM formatted private key and
  807.         certificate chain file for the SSL connection.
  808.         """
  809.         
  810.         def __init__(self, host = '', port = 0, local_hostname = None, keyfile = None, certfile = None, timeout = socket._GLOBAL_DEFAULT_TIMEOUT):
  811.             self.keyfile = keyfile
  812.             self.certfile = certfile
  813.             SMTP.__init__(self, host, port, local_hostname, timeout)
  814.             self.default_port = SMTP_SSL_PORT
  815.  
  816.         
  817.         def _get_socket(self, host, port, timeout):
  818.             if self.debuglevel > 0:
  819.                 print >>stderr, 'connect:', (host, port)
  820.             
  821.             new_socket = socket.create_connection((host, port), timeout)
  822.             new_socket = ssl.wrap_socket(new_socket, self.keyfile, self.certfile)
  823.             self.file = SSLFakeFile(new_socket)
  824.             return new_socket
  825.  
  826.  
  827.     __all__.append('SMTP_SSL')
  828.  
  829. LMTP_PORT = 2003
  830.  
  831. class LMTP(SMTP):
  832.     """LMTP - Local Mail Transfer Protocol
  833.  
  834.     The LMTP protocol, which is very similar to ESMTP, is heavily based
  835.     on the standard SMTP client. It's common to use Unix sockets for LMTP,
  836.     so our connect() method must support that as well as a regular
  837.     host:port server. To specify a Unix socket, you must use an absolute
  838.     path as the host, starting with a '/'.
  839.  
  840.     Authentication is supported, using the regular SMTP mechanism. When
  841.     using a Unix socket, LMTP generally don't support or require any
  842.     authentication, but your mileage might vary."""
  843.     ehlo_msg = 'lhlo'
  844.     
  845.     def __init__(self, host = '', port = LMTP_PORT, local_hostname = None):
  846.         '''Initialize a new instance.'''
  847.         SMTP.__init__(self, host, port, local_hostname)
  848.  
  849.     
  850.     def connect(self, host = 'localhost', port = 0):
  851.         '''Connect to the LMTP daemon, on either a Unix or a TCP socket.'''
  852.         if host[0] != '/':
  853.             return SMTP.connect(self, host, port)
  854.         
  855.         try:
  856.             self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  857.             self.sock.connect(host)
  858.         except socket.error:
  859.             host[0] != '/'
  860.             msg = host[0] != '/'
  861.             if self.debuglevel > 0:
  862.                 print >>stderr, 'connect fail:', host
  863.             
  864.             if self.sock:
  865.                 self.sock.close()
  866.             
  867.             self.sock = None
  868.             raise socket.error, msg
  869.         except:
  870.             host[0] != '/'
  871.  
  872.         (code, msg) = self.getreply()
  873.         return (code, msg)
  874.  
  875.  
  876. if __name__ == '__main__':
  877.     import sys
  878.     
  879.     def prompt(prompt):
  880.         sys.stdout.write(prompt + ': ')
  881.         return sys.stdin.readline().strip()
  882.  
  883.     fromaddr = prompt('From')
  884.     toaddrs = prompt('To').split(',')
  885.     print 'Enter message, end with ^D:'
  886.     msg = ''
  887.     while None:
  888.         line = sys.stdin.readline()
  889.         if not line:
  890.             break
  891.         
  892.         msg = msg + line
  893.         continue
  894.         print 'Message length is %d' % len(msg)
  895.         server = SMTP('localhost')
  896.         server.sendmail(fromaddr, toaddrs, msg)
  897.         server.quit()
  898. __name__ == '__main__'
  899.